export let isDragging = false;
let startX, startY;

export function initDraggable() {
  const volumeControl = document.getElementById('chrome-volume-control');
  const volumeIcon = document.getElementById('volume-icon');
  if (!volumeControl || !volumeIcon) return;

  volumeIcon.addEventListener('mousedown', startDragging);
  document.addEventListener('mousemove', drag);
  document.addEventListener('mouseup', stopDragging);

  volumeControl.addEventListener('selectstart', (e) => e.preventDefault());
}

export function updatePanelPosition() {
  const volumeControl = document.getElementById('chrome-volume-control');
  const volumePanel = document.getElementById('volume-panel');
  const rect = volumeControl.getBoundingClientRect();
  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;

  volumePanel.style.bottom = '100%';
  volumePanel.style.top = 'auto';
  volumePanel.style.margin = '0';
  volumePanel.style.position = 'absolute';
  volumePanel.style.marginBottom = '10px';

  if (rect.left < viewportWidth / 2) {
    volumePanel.style.left = '0';
    volumePanel.style.right = 'auto';
  } else {
    volumePanel.style.right = '0';
    volumePanel.style.left = 'auto';
  }

  if (isDragging) {
    volumePanel.style.display = 'block';
    volumePanel.style.opacity = '1';
    volumePanel.style.visibility = 'visible';
  }
}

function startDragging(e) {
  e.preventDefault();
  e.stopPropagation();
  isDragging = true;
  const rect = this.getBoundingClientRect();
  startX = e.clientX - rect.left;
  startY = e.clientY - rect.top;
  document.getElementById('chrome-volume-control').classList.add('dragging');
  
  const volumePanel = document.getElementById('volume-panel');
  volumePanel.style.display = 'block';
  volumePanel.style.opacity = '1';
  volumePanel.style.visibility = 'visible';
}

function drag(e) {
  if (!isDragging) return;
  const volumeControl = document.getElementById('chrome-volume-control');
  if (!volumeControl) return;

  e.preventDefault();
  e.stopPropagation();

  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewportHeight = window.innerHeight || document.documentElement.clientHeight;

  const newX = e.clientX - startX;
  const newY = e.clientY - startY;

  const right = viewportWidth - newX - volumeControl.offsetWidth;
  const bottom = viewportHeight - newY - volumeControl.offsetHeight;

  volumeControl.style.right = `${Math.max(0, right)}px`;
  volumeControl.style.bottom = `${Math.max(0, bottom)}px`;
  volumeControl.style.left = 'auto';
  volumeControl.style.top = 'auto';

  updatePanelPosition();
}

function stopDragging(e) {
  if (isDragging) {
    e.preventDefault();
    e.stopPropagation();
  }
  isDragging = false;
  const volumeControl = document.getElementById('chrome-volume-control');
  if (volumeControl) {
    volumeControl.classList.remove('dragging');
    updatePanelPosition();
  }
}